using System;
using System.Web.Mvc;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;
using MvcContrib;

namespace DecisionMaking.WebApp.Controllers
{
	[HandleError]
    [Authorize]
    public class CuesController : BaseController
	{
		/// <summary>
		/// Injected by Windsor 
		/// </summary>
		public IEnvironmentManager EnvironmentManager {private get; set;}	
		
		[HttpGet]
		public ActionResult List(int id)
		{
            var environment = EnvironmentManager.GetEnvironment(id);

            // make sure current user is owner of current environment
            if (!environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

			var cues = EnvironmentManager.GetCues(id);
		    var cueAttributes = EnvironmentManager.GetCueAttributes(id);

		    ViewData["cueAttributes"] = cueAttributes; // needed for dynamically building the columns
			ViewData["cues"] = cues;
		    ViewData["environment"] = environment;
			
			// pre-set the environment id for the new cue form model
			return View(); 
		}

        [HttpGet]
        public ActionResult Add(int id)
        {
            var environment = EnvironmentManager.GetEnvironment(id);

            // make sure current user is owner of current environment
            if (!environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            // initialize model with cue attributes in order for the page to work correctly
		    var model = new CueModel {EnvironmentId = id};
            model.InitAttributes(EnvironmentManager.GetCueAttributes(id));

            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Add(CueModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    EnvironmentManager.SaveCue(model);
                    return this.RedirectToAction(c => c.List(model.EnvironmentId));
                }
                catch (DuplicateCueNameException e)
                {
                    ModelState.AddModelError("Name", "A Cue with this name already exists.");
                }
            }

            return View("Edit", model);
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var cue = EnvironmentManager.GetCue(id);

            // make sure current user is owner of current cue
            if (!cue.Environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            var cueAttributes = EnvironmentManager.GetCueAttributes(cue.Environment.Id);

            // initialize model with cue attributes in order for the page to work correctly
            var model = new CueModel
            {
                CueId = cue.Id,
                EnvironmentId = cue.Environment.Id,
                Name = cue.Name,
                Order = cue.SortOrder,
            };

            // we go over the current list of Cue Attributes rather than use the ones in the Cue since new attributes may have been added after the Cue has been created, 
            // in which case it will not have values for these attributes
            foreach (var attribute in cueAttributes)
            {
                model.AttributeValues.Add(new CueAttributeValueModel
                {
                    CueAttributeId = attribute.Id,
                    Name = attribute.Name,
                    Value = cue.GetAttributeValue(attribute)
                });
            }

            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Edit(CueModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    EnvironmentManager.SaveCue(model);
                    return this.RedirectToAction(c => c.List(model.EnvironmentId));
                }
                catch (DuplicateCueNameException e)
                {
                    ModelState.AddModelError("Name", "A Cue with this name already exists.");
                }
                catch (AccessDeniedException e)
                {
                    return AccessDenied();
                }
                catch (EntityNotFoundException e)
                {
                    return NotFound(e);
                }
            }

            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var cue = EnvironmentManager.GetCue(id);

            // make sure current user is owner of current cue
            if (!cue.Environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            EnvironmentManager.RemoveCue(id);

            return Json(new { success = true, deletedId = id });            
        }
	}
}

